import React, { useState } from "react";
import {
  Col,
  Row,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Space,
  Table,
  Popconfirm,
  Modal,
  InputNumber,
  Image,
  Tabs,
  Radio,
} from "antd";
import "./mall.css";
import TagList from "../../components/commonTagList";
import moment from "moment";
import User from "../user/user";
import ColumnGroup from "antd/es/table/ColumnGroup";
import {listProduct} from "../../api";

const { TextArea } = Input;

const { Option } = Select;

const Mall = () => {
  const { form } = Form.useForm();
  const [ModalForm] = Form.useForm();
  const [ApproveForm] = Form.useForm();
  const [priceTypeList, setPriceTypeList] = useState([]);
  // 编辑商品弹窗是否显示
  const [editMallModal, setEditMallModal] = useState(false);
  // 当前正在编辑的商品
  const [editMall, setEditMall] = useState({});
  // 当前正在编辑的商品是否是编辑
  const [editMallEdit, setEditMallEdit] = useState(false);
  // 审批弹窗是否显示
  const [approveMallModal, setApproveMallModal] = useState(false);
  // 当前正在编辑的商品
  const [approveMall, setApproveMall] = useState({});

  // 商品列表数据
  const [dataSource, setDataSource] = useState([]);

  React.useEffect(() => {
    listProduct({
      "page":"1",
      "limit":"10"
    }).then(res => {
      console.log("res - ", res)
    })

  }, []);

  const role = localStorage.getItem("role");
  const handleSearchFinish = (values) => {
    console.log(values);
  };
  const handleReset = () => {
    console.log("click");
    form.restFileds();
  };
  // const dataSource = [
  //   {
  //     ID: "0000000000001",
  //     name: "爱奇艺会员",
  //     stock: "5",
  //     begin: "Sat Jun 08 2024 ",
  //     finish: "Sat Jun 08 2024 ",
  //     status: "1",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000002",
  //     name: "小米SU7",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "0",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000003",
  //     name: "茶π",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "0",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000004",
  //     name: "笔记本电脑",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "1",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000005",
  //     name: "缅甸一日游",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "1",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000004",
  //     name: "笔记本电脑",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "1",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000005",
  //     name: "缅甸一日游",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "1",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000004",
  //     name: "笔记本电脑",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "1",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000005",
  //     name: "缅甸一日游",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "1",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000004",
  //     name: "笔记本电脑",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "1",
  //     admin: "管理员",
  //   },
  //   {
  //     ID: "00000000005",
  //     name: "缅甸一日游",
  //     stock: "99",
  //     begin: "2024年5月1日",
  //     finish: "2025年5月1日",
  //     status: "1",
  //     admin: "管理员",
  //   },
  // ];
  const columns = [
    {
      title: "权益ID",
      dataIndex: "ID",
      key: "ID",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "商品名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "库存",
      dataIndex: "stock",
      key: "stock",
    },
    {
      title: "开始时间",
      dataIndex: "begin",
      key: "begin",
    },
    {
      title: "结束时间",
      dataIndex: "finish",
      key: "finish",
    },
    {
      title: "商品状态",
      dataIndex: "status",
      render: (val) => {
        return val ? "上线" : "下线";
      },
      filters: [
        {
          text: "上线",
          value: "1",
        },
        {
          text: "下线",
          value: "0",
        },
      ],
      filterMode: "tree",
      onFilter: (value, record) => record.status.startsWith(value),
    },

    {
      title: "管理人",
      dataIndex: "admin",
      key: "admin",
    },
    {
      title: "操作",
      render: (rowData) => {
        return (
          <div className="flex-box">
            {role !== "admin" ? (
              <>
                <Button
                  style={{ marginRight: "5px" }}
                  onClick={() => showEditMallModal(rowData, true)}
                >
                  编辑
                </Button>
              </>
            ) : null}

            <Button
              style={{ marginRight: "5px" }}
              onClick={() => showEditMallModal(rowData, false)}
            >
              查看
            </Button>
            <Popconfirm
              title="提示"
              description="此操作将下线，是否确认？"
              okText="确认"
              cancelText="取消"
              /*onConfirm={() => handle()}*/
            >
              <Button type="primary" danger style={{ marginRight: "5px" }}>
                下线
              </Button>
            </Popconfirm>
            <Button
              style={{ marginRight: "5px" }}
              type={"primary"}
              onClick={() => showApproveMallModal(rowData)}
            >
              审核
            </Button>
          </div>
        );
      },
    },
  ];
  const showEditMallModal = (rowData, isEdit) => {
    setEditMall(rowData);
    setEditMallEdit(isEdit);
    setEditMallModal(true);
    // 设置表单值
    ModalForm.setFieldsValue({
      ...rowData,
      timeOn: editMall.timeOn ? moment(editMall.timeOn) : null,
      timeOff: editMall.timeOff ? moment(editMall.timeOff) : null,
      priceTypeList: editMall.priceTypeList || [],
    });
    setPriceTypeList(editMall.priceTypeList || []);
  };
  const showApproveMallModal = (rowData) => {
    setApproveMall(rowData);
    setApproveMallModal(true);
    // 设置表单值
    ApproveForm.setFieldsValue({
      ...rowData,
    });
  };
  // 编辑商品弹窗
  const EditMallModal = () => {
    const addPriceType = () => {
      const priceTypeList = ModalForm.getFieldValue("priceTypeList") || [];
      setPriceTypeList([
        ...priceTypeList,
        { priceType: 0, pointAmount: 0, cashAmount: 0 },
      ]);
      ModalForm.setFieldsValue({
        priceTypeList: [
          ...priceTypeList,
          { priceType: 0, pointAmount: 0, cashAmount: 0 },
        ],
      });
    };
    const handleOk = () => {
      ModalForm.validateFields()
        .then((values) => {
          // 格式化时间字段
          if (values.timeOn) {
            values.timeOn = moment(values.timeOn).format("YYYY-MM-DD HH:mm:ss");
          }
          if (values.timeOff) {
            values.timeOff = moment(values.timeOff).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          }

          console.log("Success:", values);
          // 提交数据，关闭模态框
          // setEditMallModal(false);
        })
        .catch((errorInfo) => {
          console.log("Failed:", errorInfo);
        });
    };

    const handleCancel = () => {
      setEditMallModal(false);
    };

    return (
      <Modal
        title={editMallEdit ? "编辑商品" : "查看商品"}
        open={editMallModal}
        onOk={handleOk}
        onCancel={handleCancel}
        width={"1000px"}
        footer={[
          <Button key="back" onClick={handleCancel}>
            取消
          </Button>,

          editMallEdit && (
            <Button key="submit" type="primary" onClick={handleOk}>
              保存
            </Button>
          ),
        ]}
      >
        <Form form={ModalForm} name="MallForm" autoComplete="off">
          <Form.Item
            label="商品名称"
            name="productName"
            rules={[
              {
                required: editMallEdit,
                message: "请输入商品名称",
              },
            ]}
          >
            {editMallEdit ? <Input /> : editMall.productName}
          </Form.Item>

          <Row gutter={20}>
            <Col span={5}>
              <Form.Item
                label="商品图片"
                name="productPicture"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入商品图片",
                  },
                ]}
              >
                <Image width={100} src="" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="商品图片地址"
                name="productPicture"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入商品图片地址",
                  },
                ]}
              >
                {editMallEdit ? (
                  <TextArea
                    placeholder="请输入商品图片地址"
                    autoSize={{
                      minRows: 4,
                      maxRows: 4,
                    }}
                  />
                ) : (
                  editMall.productPicture
                )}
              </Form.Item>
            </Col>
            <Col span={11}>
              <Form.Item
                label="商品详情"
                name="description"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入商品详情",
                  },
                ]}
              >
                {editMallEdit ? (
                  <TextArea
                    placeholder="请输入商品详情"
                    autoSize={{
                      minRows: 4,
                      maxRows: 4,
                    }}
                  />
                ) : (
                  editMall.description
                )}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={20}>
            <Col span={12}>
              <Form.Item
                label="供应商"
                name="supplierName"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入供应商",
                  },
                ]}
              >
                {editMallEdit ? <Input /> : editMall.supplierName}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="供应商联系方式"
                name="supplierPhonenumber"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入供应商联系方式",
                  },
                ]}
              >
                {editMallEdit ? <Input /> : editMall.supplierPhonenumber}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={20}>
            <Col span={12}>
              <Form.Item
                label="初始库存"
                name="initStock"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入初始库存",
                  },
                ]}
              >
                {editMallEdit ? (
                  <InputNumber style={{ width: "100%" }} />
                ) : (
                  editMall.supplierPhonenumber
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="剩余库存"
                name="remainingStock"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入剩余库存",
                  },
                ]}
              >
                {editMallEdit ? (
                  <InputNumber style={{ width: "100%" }} />
                ) : (
                  editMall.supplierPhonenumber
                )}
              </Form.Item>
            </Col>
          </Row>

          <Form.Item label="支付方式" required={editMallEdit}>
            {editMallEdit && (
              <Button type="primary" onClick={addPriceType}>
                添加
              </Button>
            )}

            <Form.List name="priceTypeList">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, fieldKey, ...restField }) => (
                    <div key={key}>
                      <Row gutter={20}>
                        <Col>
                          <Form.Item
                            {...restField}
                            label={"支付方式"}
                            name={[name, "priceType"]}
                            fieldKey={[fieldKey, "priceType"]}
                            rules={[
                              { required: true, message: "请选择支付方式" },
                            ]}
                          >
                            <Select
                              style={{ width: 170 }}
                              options={[
                                { label: "积分方式", value: 0 },
                                { label: "现金支付", value: 1 },
                                { label: "混合支付", value: 2 },
                              ]}
                              onChange={(value) => {
                                const newPriceTypeList = [...priceTypeList];
                                newPriceTypeList[key].priceType = value;
                                setPriceTypeList(newPriceTypeList);
                              }}
                            />
                          </Form.Item>
                        </Col>
                        {priceTypeList[key]?.priceType !== 1 && (
                          <Col>
                            <Form.Item
                              {...restField}
                              label={"积分数量"}
                              name={[name, "pointAmount"]}
                              fieldKey={[fieldKey, "pointAmount"]}
                              rules={[
                                {
                                  required: priceTypeList[key]?.priceType !== 1,
                                  message: "请输入积分数量",
                                },
                              ]}
                            >
                              <InputNumber style={{ width: 120 }} />
                            </Form.Item>
                          </Col>
                        )}
                        {priceTypeList[key]?.priceType !== 0 && (
                          <Col>
                            <Form.Item
                              {...restField}
                              label={"现金金额"}
                              name={[name, "cashAmount"]}
                              fieldKey={[fieldKey, "cashAmount"]}
                              rules={[
                                {
                                  required: priceTypeList[key]?.priceType !== 0,
                                  message: "请输入现金金额",
                                },
                              ]}
                            >
                              <InputNumber style={{ width: 120 }} />
                            </Form.Item>
                          </Col>
                        )}

                        {editMallEdit && (
                          <Col>
                            <Button type="danger" onClick={() => remove(name)}>
                              删除
                            </Button>
                          </Col>
                        )}
                      </Row>
                    </div>
                  ))}
                </>
              )}
            </Form.List>
          </Form.Item>

          <Form.Item
            label="服务保障"
            name="serviceGuarantee"
            rules={[
              {
                required: editMallEdit,
                message: "请输入服务保障",
              },
            ]}
          >
            {editMallEdit ? <Input /> : editMall.serviceGuarantee}
          </Form.Item>
          <Form.Item
            label="兑换限制"
            name="exchangeRestrictions"
            rules={[
              {
                required: editMallEdit,
                message: "请输入兑换限制",
              },
            ]}
          >
            {editMallEdit ? (
              <InputNumber style={{ width: "100%" }} />
            ) : (
              editMall.exchangeRestrictions
            )}
          </Form.Item>

          <Row gutter={20}>
            <Col span={12}>
              <Form.Item
                label="上线时间"
                name="timeOn"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入上线时间",
                  },
                ]}
              >
                {editMallEdit ? (
                  <DatePicker showTime style={{ width: "100%" }} />
                ) : (
                  editMall.timeOn
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="下线时间"
                name="timeOff"
                rules={[
                  {
                    required: editMallEdit,
                    message: "请输入下线时间",
                  },
                ]}
              >
                {editMallEdit ? (
                  <DatePicker showTime style={{ width: "100%" }} />
                ) : (
                  editMall.timeOff
                )}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={20}>
            <Col span={12}>
              <Form.Item
                label="城市白名单"
                name="cityWhitelist"
                rules={[
                  {
                    required: false,
                    message: "请输入城市白名单",
                  },
                ]}
              >
                <TagList editMallEdit={editMallEdit} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="城市黑名单"
                name="cityBlacklist"
                rules={[
                  {
                    required: false,
                    message: "请输入城市黑名单",
                  },
                ]}
              >
                <TagList editMallEdit={editMallEdit} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  };

  // 审批弹窗
  const ApproveModel = () => {
    const handleOk = () => {
      ApproveForm.validateFields()
        .then((values) => {
          console.log("Success:", values);
          // 提交数据，关闭模态框
          // setEditMallModal(false);
        })
        .catch((errorInfo) => {
          console.log("Failed:", errorInfo);
        });
    };

    const handleCancel = () => {
      setApproveMallModal(false);
    };

    return (
      <Modal
        title="审核商品"
        open={approveMallModal}
        onOk={handleOk}
        onCancel={handleCancel}
        width={"1000px"}
        footer={[
          <Button key="back" onClick={handleCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleOk}>
            保存
          </Button>,
        ]}
      >
        <Form form={ApproveForm} name="ApproveForm" autoComplete="off">
          <Form.Item
            label="审核结果"
            name="result"
            rules={[
              {
                required: true,
                message: "请选择审核结果",
              },
            ]}
          >
            <Radio.Group>
              <Radio value={1}>通过</Radio>
              <Radio value={2}>不通过</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="不通过原因"
            name="reason"
            rules={[
              {
                required: false,
                message: "请输入不通过原因",
              },
            ]}
          >
            <TextArea
              placeholder="请输入不通过原因"
              autoSize={{
                minRows: 4,
                maxRows: 4,
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  return (
    <div className="">
      <Form
        onFinish={handleSearchFinish}
        name="search"
        initialValues={{
          ID: "",
          name: "",
          begin: "",
          finish: "",
          status: "",
          admin: "",
        }}
      >
        <Row gutter={[10, 8]}>
          <Col span={6}>
            <Form.Item name="ID" label="权益ID">
              <Input placeholder="请输入" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="name" label="商品名称">
              <Input placeholder="请输入" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="begin" label="开始时间">
              <DatePicker placeholder="请选择" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="finish" label="结束时间">
              <DatePicker placeholder="请选择" />
            </Form.Item>
          </Col>

          <Col span={6}>
            <Form.Item name="status" label="商品状态">
              <Select showSearch placeholder="请选择">
                <Option value="1">上线</Option>
                <Option value="0">下线</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="admin" label="管理人">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
          </Col>
          <Col span={6}></Col>
          <Col span={6}>
            <Space>
              <Button htmlType="reset" onClick={handleReset}>
                重置
              </Button>
              <Button htmlType="submit" type="primary">
                查询
              </Button>
              <Button type="primary" onClick={showEditMallModal}>
                新增
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
      <Table dataSource={dataSource} columns={columns}>
        <caption>商品列表</caption>
      </Table>

      {/*编辑商品弹窗*/}
      <EditMallModal />

      {/*审批弹窗*/}
      <ApproveModel />
    </div>
  );
};
export default Mall;
